package com.axs.camera.adapter;

import android.os.Environment;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.axs.camera.R;
import com.bumptech.glide.Glide;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> {
    private File[] files;

    public PhotoAdapter(File[] files) {
        this.files = files;
    }

    @NonNull
    @Override
    public PhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new PhotoViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull PhotoViewHolder holder, int position) {
        File file = files[position];

        holder.tvPlant.setText(getChinese(file.getName()));
        //加载图片
        Glide.with(holder.ivPhoto.getContext()).load(file).into(holder.ivPhoto);
    }

    @Override
    public int getItemCount() {
        return files.length;
    }

    public String getChinese(String s) {
        StringBuffer stringBuffer = new StringBuffer();
        for (char c : s.toCharArray()) {
            try {
                if (String.valueOf(c).getBytes("UTF-8").length > 1) {
                    stringBuffer.append(c);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return stringBuffer.toString();
    }

    static class PhotoViewHolder extends RecyclerView.ViewHolder {
        ImageView ivPhoto;
        TextView tvPlant;

        public PhotoViewHolder(@NonNull View itemView) {
            super(itemView);

            ivPhoto = itemView.findViewById(R.id.iv_photo);
            tvPlant = itemView.findViewById(R.id.tv_plant);
        }
    }
}
